import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yi_shop/model/product.dart';
import 'package:yi_shop/route/index.dart';
import 'package:yi_shop/ui/scroll_refresh_config.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/tools.dart';

class GroupBuyController extends GetxController {
  RxList<GroupBuyProductModel> pageList = RxList([]);

  RefreshController refreshController = RefreshController();

  @override
  void onInit() {
    initData();
    super.onInit();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 30) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    initData();

    /// 完毕
    refreshController.loadComplete();
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(GroupBuyProductModel(
          imgUrl: 'https://t15.baidu.com/it/u=84183866,143092700&fm=224&app=112&f=JPEG?w=500&h=500',
          name: '恒威第五代强力燃油宝积碳清洁剂50ml',
          count: r.nextInt(1000),
          unit: '瓶',
          originalPrice: 200.00 + r.nextInt(500),
          sellPrice: 100.00 + r.nextInt(300),
          groupCount: r.nextInt(10)));
    }
  }
}

class GroupBuyPage extends GetView<GroupBuyController> {
  const GroupBuyPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: ToolsUtils.builderLeading(),
        title: const Text('团购专区'),
      ),
      body: Obx(() => scrollRefreshConfig(context)),
    );
  }

  ScrollRefreshConfig scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: listViewBuilder(context),
    );
  }

  Widget listViewBuilder(BuildContext context) {
    return ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        final row = controller.pageList[index];
        return InkWell(
          onTap: () {
            Get.toNamed(RoutePath.groupInfo);
          },
          child: Container(
            margin: EdgeInsets.only(top: 15.h),
            alignment: Alignment.center,
            child: Container(
              width: 345.w,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5.r),
                  boxShadow: [
                    BoxShadow(
                      offset: const Offset(1.0, 1.0),
                      color: ColorsUtils.rgba(0, 0, 0, 0.349019607843137),
                      blurRadius: 5.w,
                      spreadRadius: 0.0,
                      blurStyle: BlurStyle.outer,
                    )
                  ]),
              padding: EdgeInsets.all(10.w),
              child: Column(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(5.r),
                    child: CachedNetworkImage(
                      imageUrl: row.imgUrl,
                      height: 115.h,
                      width: double.infinity,
                      fit: BoxFit.fill,
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 10.w),
                    alignment: Alignment.centerLeft,
                    child: Text('${row.name} x ${row.count}${row.unit}',
                        style: StylesUtils.textStyle(
                            color: ColorsUtils.rgba(0, 0, 0, 0.847058823529412))),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 8.w),
                    alignment: Alignment.centerLeft,
                    child: RichText(
                      text: TextSpan(children: [
                        TextSpan(
                            text: '￥${row.sellPrice}起  ',
                            style: StylesUtils.customTextStyle(
                              color: ColorsUtils.colorE419,
                            )),
                        TextSpan(
                            text: '原价：￥${row.originalPrice}',
                            style: StylesUtils.customTextStyle(
                              color: ColorsUtils.color9999,
                              decoration: TextDecoration.lineThrough,
                              decorationColor:
                                  ColorsUtils.parseColorFromHexString(ColorsUtils.color9999),
                              decorationThickness: 1.0,
                              decorationStyle: TextDecorationStyle.solid,
                            ))
                      ]),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 8.w),
                    alignment: Alignment.centerLeft,
                    child: Text('最低${row.groupCount}人成团'),
                  )
                ],
              ),
            ),
          ),
        );
      },
      itemCount: controller.pageList.length,
    );
  }
}
